<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var data = [
        [1, 2],
        [2, 1],
        [7, 4],
        [8, 1],
        [9, 2],
        [10, 8],
        [8, 11],
        [9, 9],
      ];
      let c0 = data[0];
      let c1 = data[1];

      // 计算欧氏距离
      function calculateDistance(center, points) {
        let dx = center[0] - points[0];
        let dy = center[1] - points[1];
        let range = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
        return range;
      }
      // 将点进行分类
      function pointsCategory(c0, c1) {
        let k0 = [];
        let k1 = [];
        for (const key in data) {
          // 计算每个点到中心点的距离
          // 离哪个近就推到哪个数组中
          let range0 = calculateDistance(c0, data[key]);
          let range1 = calculateDistance(c1, data[key]);
          if (range0 > range1) {
            // 0大于1属于第一类的点
            k1.push(data[key]);
          } else if (range0 < range1) {
            // 属于第二类
            k0.push(data[key]);
          } else {
            // 随机分配
            k0.push(data[key]);
          }
        }
        let newC0 = calculateAverage(k0);
        let newC1 = calculateAverage(k1);
        console.log(k0, k1);
        console.log(newC0, newC1, c0, c1);
        if (
          Math.abs(newC1[0] - c1[0]) < 0.1 &&
          Math.abs(newC0[0] - c0[0]) < 0.1
        ) {
          return {
            k0,
            k1,
          };
        } else {
          return pointsCategory(newC0, newC1);
        }
      }
      // 生成中心点
      function calculateAverage(k) {
        var num = 0;
        var sum = 0;
        var i = 0;
        var j = 0;
        let center = [];
        for (i = 0; i < k[j % k.length].length; i++) {
          sum = 0;
          for (j = 0; j < k.length; j++) {
            sum += k[j][i];
          }
          center.push(sum / k.length);
        }
        return center;
      }
      console.log(pointsCategory(c0, c1));
    </script>
  </body>
</html>
